import { useLocalStorage } from '@vueuse/core'
import { useIssueStore } from './issueStore'
import { useUserStore } from '@/stores/user'

export interface Comment {
  id: number
  message: string
  publisher: string
  publisherID: string
  targetID: string
  targetName: string
  issueID: number
  passed: boolean
  hasReplied: boolean
  createdAt: string
}

export function useCommentStore() {
  const userStore = useUserStore()
  const issueStore = useIssueStore()
  const comments = useLocalStorage<Comment[]>('comments', [], {
    deep: true,
    listenToStorageChanges: true
  })

  const updateComment = (id: number, comment: Comment) => {
    const index = comments.value.findIndex((comment) => comment.id === id)
    if (index !== -1) {
      comments.value[index] = comment
    }
  }

  const repliedComment = (id: number) => {
    const comment = comments.value.find((comment) => comment.id === id)
    comment && updateComment(id, { ...comment, hasReplied: true })
  }

  const notifyHasAssigned = (issueId: number) => {
    const pendingComments = comments.value.filter(
      (comment) => comment.issueID === issueId && comment.hasReplied === false
    )

    for (const comment of pendingComments) {
      updateComment(comment.id, {
        ...comment,
        hasReplied: true,
        message: '教师已指派该课题人选, 请选择其它课题',
        passed: false
      })
    }
  }

  const removeComment = (id: number) => {
    comments.value = comments.value.filter((comment) => comment.id !== id)
  }

  const addComment = (comment: Omit<Comment, 'id' | 'createdAt' | 'publisher' | 'publisherID'>) => {
    const id = comments.value.reduce((newId, { id }) => (newId > id ? newId : id + 1), 1)

    comments.value.push({
      ...comment,
      publisher: userStore.user.name,
      publisherID: userStore.user.username,
      id,
      createdAt: new Date().toISOString()
    })

    if (comment.passed) {
      const issue = issueStore.searchIssueById(comment.issueID)
      if (issue?.status === false) {
        issueStore.updateIssue(comment.issueID, { ...issue, status: true })
        notifyHasAssigned(comment.issueID)
      }
    }
  }

  return {
    comments,

    addComment,
    removeComment,
    repliedComment,
    updateComment
  }
}
